package com.app.mymusic.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.app.mymusic.common.Constants;
import com.app.mymusic.model.Mp3Info;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**
 * Created by Administrator on 2016/8/1.
 */
public class MySqlOpenHelper extends OrmLiteSqliteOpenHelper {

    private Dao<Mp3Info,Integer> mp3Dao;
    private static MySqlOpenHelper helper;

    public MySqlOpenHelper(Context context)
    {
        super(context, Constants.DB_DOWNLOAD, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTableIfNotExists(connectionSource, Mp3Info.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource,Mp3Info.class,true);
            onCreate(database,connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public Dao<Mp3Info,Integer> getUserDao() throws java.sql.SQLException
    {
        if(mp3Dao==null)
        {
            mp3Dao=getDao(Mp3Info.class);
        }
        return mp3Dao;
    }

    public static MySqlOpenHelper getMySqlOpenHelper(Context context)
    {
        context = context.getApplicationContext();
        if(helper==null)
       {
           synchronized (MySqlOpenHelper.class)
           {
               helper=new MySqlOpenHelper(context);
           }
       }
        return  helper;
    }
}
